
from typing import Any
from flask import Flask, request, jsonify , Response
from flask_cors import CORS

from sympy import * # type: ignore

def create_remote_app(remoteUrl: str = '/RPC_PAO', funcs: dict[Function] | list[Function] = {}) -> Flask:
	app = Flask(__name__)

	@app.route(remoteUrl, methods=['POST'])
	def remote_call():
		if not request.is_json :
			return jsonify({"status": "error", "message": 'Request must be JSON'}), 400
		try:
			data: Any = request.json
			func_name: str = data['func']
			args: any = data['args']
			print(f"func: {func_name}, args: {args}")
			
			if type(funcs) == list:
				for f in funcs:
					if f.__name__ == func_name:
						fun = f
						break
				else:
					return jsonify({"status": "error", "message": f"Function {func_name} not found"}), 400
			else:
				fun = funcs.get(func_name)
				if not fun:
					return jsonify({"status": "error", "message": f"Function {func_name} not found"}), 400
				
			fun = fun or globals().get(func_name)
			ret_val = fun(*args)
			return jsonify(ret_val), 200
		except Exception as e:
			print(f"Error: {e}")
			return jsonify({"status": "error", "message": str(e)}), 400

  # 支持跨域访问
	CORS(app)

	return app

